﻿@page "/useraccounts/delete"

@using Microsoft.EntityFrameworkCore
@using BlazorAppAuth.Models
@inject IDbContextFactory<BlazorAppAuth.Data.BlazorAppAuthContext> DbFactory
@inject NavigationManager NavigationManager


<PageTitle>Delete</PageTitle>

<h1>Delete</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>UserAccount</h4>
    <hr />
    @if (useraccount is null)
    {
        <p><em>Loading...</em></p>
    }
    else {
        <dl class="row">
            <dt class="col-sm-2">Name</dt>
            <dd class="col-sm-10">@useraccount.Name</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Password</dt>
            <dd class="col-sm-10">@useraccount.Password</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Role</dt>
            <dd class="col-sm-10">@useraccount.Role</dd>
        </dl>
        <EditForm method="post" Model="useraccount" OnValidSubmit="DeleteUserAccount" FormName="delete" Enhance>
            <button type="submit" class="btn btn-danger" disabled="@(useraccount is null)">Delete</button> |
            <a href="/useraccounts">Back to List</a>
        </EditForm>
    }
</div>

@code {
    UserAccount? useraccount;

    [SupplyParameterFromQuery]
    public int Id { get; set; }

    protected override async Task OnInitializedAsync()
    {
        using var context = DbFactory.CreateDbContext();
        useraccount = await context.UserAccount.FirstOrDefaultAsync(m => m.Id == Id);

        if (useraccount is null)
        {
            NavigationManager.NavigateTo("notfound");
        }
    }

    public async Task DeleteUserAccount()
    {
        using var context = DbFactory.CreateDbContext();
        context.UserAccount.Remove(useraccount!);
        await context.SaveChangesAsync();
        NavigationManager.NavigateTo("/useraccounts");
    }
}
